import {Component, OnInit, Renderer2} from '@angular/core';
import {WebsocketService} from "@core/services/websocket/websocket.service";
import {Router} from "@angular/router";
import {Subscription} from "rxjs/internal/Subscription";
import * as CryptoJS from 'crypto-js';
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import {ApiService} from "@core/services/http/api.service";
import {of} from "rxjs/internal/observable/of";
import {concatMap} from "rxjs/operators";
import { DomSanitizer } from '@angular/platform-browser';
import {AnalysisService} from "../analysis.service";

@Component({
  selector: 'all-control',
  templateUrl: './all-control.component.html',
  styleUrls: ['./all-control.component.scss']
})
export class AllControlComponent implements OnInit {
  messagesSubscription: Subscription;
  today = new Date();
  isVisible: boolean = false;                       // 为true时弹出登录对话窗
  wsId: string;                                     // WebsocketService 唯一标识
  times = new Date().getTime();                     // 初次打开页面时间戳(需保存至local)
  local = this.userAuthService.getUserInfoObj();
  num = Math.floor(Math.random() * 100 + 1);
  posts = [];                                       // 岗位列表
  isMenu: boolean = false;                          // 为true时弹出退出登录选项框
  host = window.location.host;
  year: any;

  reportData = [
    {title: '商务总控', href: '/analysis/totalControl'},
    {title: '门管总控', href: '/analysis/doorControl'},
    {title: '客服总控', href: '/analysis/customServiceControl'},
    {title: '采购总控', href: '/analysis/purchaseControl'},
    {title: '车辆总控', href: '/analysis/carControl'}
  ];
  postsBut = {name: '退出登录', id: 'esc'};

  constructor(private ws: WebsocketService,
              private router: Router,
              private msg: ApesMessageService,
              private renderer: Renderer2,
              private userAuthService: UserAuthService,
              private apiService: ApiService,
              private sanitizer: DomSanitizer,
              private as: AnalysisService,
  ) {
    this.wsId = CryptoJS.MD5(this.times + '' + typeof this.num).toString(CryptoJS.enc.Hex);
    this.ws.connect(this.wsId);
  }

  ngOnInit() {
    const date = new Date();
    this.year = date.getFullYear();

    if (!this.local) {
      this.isVisible = true;
      this.getWebSocket();
      setTimeout(() => {
        this.initFocus();
      }, 1000);
    } else {
      // 判断距离上一次登录是否相差15天 是否需要重新登录
      setTimeout(() => {
        this.initFocus();
      }, 1000);
      const userInfo = this.userAuthService.getUserInfoObj();
      this.posts = userInfo.userAccount.posts;
      this.posts.push(this.postsBut);
    }
  }

  changeUrl(https:string, url) {
    const href = this.sanitizer.bypassSecurityTrustResourceUrl(https + url);
    return href;
  }

  /** 调用 websocket **/
  getWebSocket() {
    this.messagesSubscription = this.ws.messagesObserver.pipe(concatMap(data => {
      return of(data);
    })).subscribe(
      (item) => {
        const data = JSON.parse(item);
        if (data.topic === 'ws.loginTV') {
          let userInfo = {'token': data.sessionId, 'userAccount': data.user};
          this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
          this.as.getLocalPermit(userInfo.userAccount.post.localPermit.id);
          // 登录成功 获取公司
          this.isVisible = false;
          this.posts = userInfo.userAccount.posts;
          this.posts.push(this.postsBut);
          this.msg.info('欢迎 ' + data.user.name + ' 登录成功');
          this.local = window.localStorage['currentUser'];
        }
      });
  }

  getMouse($event:any){
    let key = $event.button;
    if( key === 2 ) {
      $event.returnValue=false;
      return false;
    }
  }

  private $(id) {
    return document.getElementById(id);
  }

  // 获取焦点
  initFocus() {
    this.$('system').focus();
  }

  getFocus(){}

  getKey($event, index, click?:any) {
    let key = $event.keyCode;
    if(click === 1){
      key = 0;
    }else if(click === 2) {
      if(this.local) {
        this.router.navigateByUrl(this.reportData[index].href);
      }else {
        this.msg.error('请刷新后扫码登录');
      }
    }
    if(key === 0 ) {
      if(this.local) {
        this.isMenu = true;
      }else {
        this.msg.error('请刷新后扫码登录');
      }
    }else {
      $event.preventDefault();
    }
    this.initFocus();
  }

  /** 获取对话框焦点 ***/
  focusMenu(id) {
    this.$('total').blur();
    this.$(id).focus();
  }

  getMenus(key) {}

  changeMenu($event, postId: string, index, click?:any) {
    $event.preventDefault();           // 阻止默认事件
    let key = $event.keyCode;
    if(click === 1){
      key = 13;
    }
    let id = $event.target.id;
    let nextId;

    switch (key) {
      case 13:
        if (id != 'esc') {
          this.changePost(postId);
        } else {
          window.localStorage.clear();
          window.location.reload(true);
          setTimeout(()=>{
            this.isVisible = true;
          },500)
        }
        this.isMenu = false;
        break;
      case 38:
        if (index <= 0) {
          index = this.posts.length - 1;
          nextId = this.posts[index].id;
        } else {
          nextId = this.posts[index - 1].id;
        }
        this.$(nextId).focus();
        break;
      case 40:
        if (index >= this.posts.length - 1) {
          index = 0;
          nextId = this.posts[index].id;
        } else {
          nextId = this.posts[index + 1].id;
        }
        this.$(nextId).focus();
        break;
    }
  }

  changePost(postId: string) {
    // 检查数据的正确性
    let currentPost = this.posts.filter((post) => post.id == postId);
    if (currentPost.length === 0)
      return;
    // 检查是否改变 post
    let userInfo = this.userAuthService.getUserInfoObj();
    let currentPostInfo = userInfo.userAccount.post;
    if (postId === currentPostInfo.id)
      return;
    // 重新请求后端刷新菜单
    this.apiService.post('aut.user.bindPost', {'body': JSON.stringify({post: {id: postId}})}).subscribe(
      (body) => {
        userInfo.userAccount.post = currentPost[0];
        this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
        const postsData = userInfo.userAccount['localPermit'];
        //   .map(item => {
        //   const postId = userInfo.userAccount.post.company.id;
        //   if (postId === item.id) {
        //     return {name: item.name, id: item.id, checked: true}
        //   } else {
        //     return {name: item.name, id: item.id, checked: false}
        //   }
        // });
        const userCompany: any = this.as.unique(postsData);
        this.as.storeLocal(JSON.stringify(userCompany));
      });
  }

}
